import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import {
  Container,
  Grid,
  Card,
  CardMedia,
  CardContent,
  Typography,
  IconButton,
  Box,
  CircularProgress,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
  Divider,
  useTheme,
  useMediaQuery,
  InputAdornment,
  Alert,
  LinearProgress,
  Fade,
  Zoom,
  Checkbox,
  Stack
} from '@mui/material';
import {
  Delete as DeleteIcon,
  Edit as EditIcon,
  MoreVert as MoreVertIcon,
  Add as AddIcon,
  Download as DownloadIcon,
  Restore as RestoreIcon,
  DeleteForever as DeleteForeverIcon,
  Refresh as RefreshIcon,
  BrokenImage as BrokenImageIcon,
  VolumeUp as VolumeUpIcon,
  VolumeOff as VolumeOffIcon,
  ArrowBack as ArrowBackIcon,
  CreateNewFolder as CreateNewFolderIcon,
  PhotoLibrary as PhotoLibraryIcon,
  ViewModule as ViewModuleIcon,
  Search as SearchIcon,
  Close as CloseIcon,
  Upload as UploadIcon
} from '@mui/icons-material';
import axios from 'axios';
import { Canvas } from '@react-three/fiber';
import { OrbitControls, useTexture, Text, Stars } from '@react-three/drei';
import * as THREE from 'three';
import ImagePreviewDialog from '../components/ImagePreviewDialog';
import imageCompression from 'browser-image-compression';

// 使用环境变量中的 API URL
const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000';

// 获取当前日期的年月日路径
const getDatePath = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}/${month}/${day}`;
};

// 3D照片组件（用于照片雨效果）
function Photo3D({ photo, position, onClick }) {
  const texture = useTexture(`${API_URL}/uploads/thumbnails/${photo.datePath}/${photo.filename}`);
  const meshRef = useRef();
  const [hovered, setHovered] = useState(false);

  useEffect(() => {
    if (meshRef.current) {
      document.body.style.cursor = hovered ? 'pointer' : 'auto';
      meshRef.current.scale.set(hovered ? 1.05 : 1, hovered ? 1.05 : 1, 1);
    }
  }, [hovered]);

  return (
    <mesh
      ref={meshRef}
      position={position}
      onClick={onClick}
      onPointerOver={() => setHovered(true)}
      onPointerOut={() => setHovered(false)}
    >
      <planeGeometry args={[1, 1]} />
      <meshBasicMaterial map={texture} />
    </mesh>
  );
}

// 3D场景组件
function Scene({ photos, onPhotoClick }) {
  const [photoPositions, setPhotoPositions] = useState([]);
  
  useEffect(() => {
    // 初始化照片位置
    const initialPositions = photos.map(() => ({
      x: (Math.random() - 0.5) * 20, // 随机x位置
      y: 20 + Math.random() * 10,    // 从上方开始
      z: (Math.random() - 0.5) * 20, // 随机z位置
      rotation: Math.random() * Math.PI * 2, // 随机旋转
      speed: 0.05 + Math.random() * 0.1, // 随机下落速度
    }));
    setPhotoPositions(initialPositions);
  }, [photos]);

  useEffect(() => {
    // 更新照片位置
    const animationFrame = requestAnimationFrame(() => {
      setPhotoPositions(prevPositions => 
        prevPositions.map(pos => {
          let newY = pos.y - pos.speed;
          // 如果照片落到底部，重新从顶部开始
          if (newY < -10) {
            newY = 20 + Math.random() * 10;
          }
          return {
            ...pos,
            y: newY,
            rotation: pos.rotation + 0.01, // 缓慢旋转
          };
        })
      );
    });

    return () => cancelAnimationFrame(animationFrame);
  }, [photoPositions]);

  return (
    <>
      {/* 深蓝色背景 */}
      <color attach="background" args={['#0a1a2a']} />
      
      {/* 添加星星 */}
      <Stars radius={100} depth={50} count={5000} factor={4} saturation={0} fade speed={1} />

      {/* 添加环境光 */}
      <ambientLight intensity={0.8} />
      <pointLight position={[10, 10, 10]} intensity={0.2} />

      {/* 照片雨效果 */}
      {photos.map((photo, index) => {
        const position = photoPositions[index];
        if (!position) return null;
        
        return (
          <group
            key={`${index}-${photo._id}`}
            position={[position.x, position.y, position.z]}
            rotation={[0, position.rotation, 0]}
          >
            <Photo3D
              photo={photo}
              position={[0, 0, 0]}
              onClick={() => onPhotoClick(photo)}
            />
          </group>
        );
      })}

      {/* 相机控制 */}
      <OrbitControls
        enableZoom={true}
        enablePan={true}
        enableRotate={true}
        minDistance={5}
        maxDistance={30}
        autoRotate
        autoRotateSpeed={0.5}
        dampingFactor={0.05}
        target={[0, 0, 0]}
      />
    </>
  );
}

// 2D照片雨组件
function PhotoRain({ photos, onPhotoClick, onClose }) {
  const [isPlaying, setIsPlaying] = useState(true);
  const [isAnimating, setIsAnimating] = useState(true);
  const audioRef = useRef(null);
  const [loadedPhotos, setLoadedPhotos] = useState(new Set());
  const [validPhotos, setValidPhotos] = useState([]);
  const [failedPhotos, setFailedPhotos] = useState(new Set());

  // 检查照片是否存在
  const checkPhotoExists = async (photo) => {
    try {
      const response = await fetch(`${API_URL}/uploads/thumbnails/${photo.datePath}/${photo.filename}`, {
        method: 'HEAD'
      });
      return response.ok;
    } catch (error) {
      console.error('检查照片失败:', error);
      return false;
    }
  };

  // 初始化时检查所有照片
  useEffect(() => {
    const validatePhotos = async () => {
      const validPhotosList = [];
      for (const photo of photos) {
        if (!failedPhotos.has(photo._id)) {
          const exists = await checkPhotoExists(photo);
          if (exists) {
            validPhotosList.push(photo);
          } else {
            setFailedPhotos(prev => new Set([...prev, photo._id]));
          }
        }
      }
      setValidPhotos(validPhotosList);
    };

    if (photos && photos.length > 0) {
      validatePhotos();
    }
  }, [photos, failedPhotos]);

  // 处理图片加载错误
  const handleImageError = (photoId) => {
    setFailedPhotos(prev => new Set([...prev, photoId]));
    setLoadedPhotos(prev => {
      const newSet = new Set(prev);
      newSet.delete(photoId);
      return newSet;
    });
  };

  // 处理图片加载成功
  const handleImageLoad = (photoId) => {
    setLoadedPhotos(prev => {
      const newSet = new Set(prev);
      newSet.add(photoId);
      return newSet;
    });
  };

  // 使用 useMemo 缓存照片的位置和动画参数
  const photoAnimations = useMemo(() => {
    if (!validPhotos || validPhotos.length === 0) return [];

    // 过滤掉加载失败的照片
    const workingPhotos = validPhotos.filter(photo => !failedPhotos.has(photo._id));
    if (workingPhotos.length === 0) return [];

    // 计算每张照片需要重复的次数，以确保铺满屏幕
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;
    const photoWidth = 150;
    const photoHeight = 150;
    const minPhotosPerRow = Math.ceil(screenWidth / photoWidth);
    const minRows = Math.ceil(screenHeight / photoHeight);
    const totalPhotosNeeded = minPhotosPerRow * minRows;
    const repeatCount = Math.ceil(totalPhotosNeeded / workingPhotos.length);

    // 生成所有照片的动画参数
    const animations = [];
    for (let i = 0; i < workingPhotos.length * repeatCount; i++) {
      const photoIndex = i % workingPhotos.length;
      const photo = workingPhotos[photoIndex];
      
      // 计算基础位置
      const row = Math.floor(i / minPhotosPerRow);
      const col = i % minPhotosPerRow;
      const baseX = (col * photoWidth) + (Math.random() * 50 - 25);
      const baseY = -photoHeight - (row * photoHeight);
      
      // 优化动画参数
      const duration = 8 + Math.random() * 4;
      const rotation = Math.random() * 360;
      const scale = 0.8 + Math.random() * 0.4;
      const horizontalSpeed = (Math.random() - 0.5) * 1.5;
      const startDelay = 0; // 移除延时

      animations.push({
        photo,
        baseX,
        baseY,
        duration,
        rotation,
        scale,
        horizontalSpeed,
        startDelay
      });
    }

    return animations;
  }, [validPhotos, failedPhotos]);

  useEffect(() => {
    audioRef.current = new Audio('/rain.mp3');
    audioRef.current.loop = true;
    
    if (isPlaying) {
      audioRef.current.play().catch(error => {
        console.log('自动播放被阻止:', error);
      });
    }

    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current = null;
      }
    };
  }, [isPlaying]);

  const toggleMusic = (e) => {
    e.stopPropagation();
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause();
      } else {
        audioRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  return (
    <Box
      sx={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)',
        zIndex: 1000,
        overflow: 'hidden',
        '&::before': {
          content: '""',
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'radial-gradient(circle at 50% 50%, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0.4) 70%)',
          pointerEvents: 'none',
        }
      }}
    >
      {/* 顶部控制栏 */}
      <Box
        sx={{
          position: 'absolute',
          top: 16,
          right: 16,
          zIndex: 1001,
          display: 'flex',
          gap: 2,
        }}
      >
        <IconButton 
          onClick={toggleMusic}
          sx={{ 
            bgcolor: 'rgba(255, 255, 255, 0.9)',
            backdropFilter: 'blur(10px)',
            color: '#2196F3',
            boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
            width: 48,
            height: 48,
            '&:hover': {
              bgcolor: '#ffffff',
              transform: 'translateY(-2px)',
              boxShadow: '0 6px 16px rgba(0,0,0,0.08)',
            },
            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
          }}
        >
          {isPlaying ? <VolumeUpIcon sx={{ fontSize: 28 }} /> : <VolumeOffIcon sx={{ fontSize: 28 }} />}
        </IconButton>
        <IconButton 
          onClick={onClose} 
          sx={{ 
            bgcolor: 'rgba(255, 255, 255, 0.9)',
            backdropFilter: 'blur(10px)',
            color: '#f44336',
            boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
            width: 48,
            height: 48,
            '&:hover': {
              bgcolor: '#ffffff',
              transform: 'translateY(-2px)',
              boxShadow: '0 6px 16px rgba(0,0,0,0.08)',
            },
            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
          }}
        >
          <ArrowBackIcon sx={{ fontSize: 28 }} />
        </IconButton>
      </Box>

      {/* 照片雨容器 */}
      <Box
        sx={{
          width: '100%',
          height: '100%',
          position: 'relative',
          overflow: 'hidden',
          willChange: 'transform',
        }}
      >
        {validPhotos.length === 0 || photoAnimations.length === 0 ? (
          <Box
            sx={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              color: 'rgba(0, 0, 0, 0.5)',
              textAlign: 'center',
            }}
          >
            <Typography variant="h6">暂无照片</Typography>
          </Box>
        ) : (
          photoAnimations.map(({ photo, baseX, baseY, duration, rotation, scale, horizontalSpeed, startDelay }, index) => (
            <Box
              key={`${photo._id}-${index}`}
              onClick={() => onPhotoClick(photo)}
              sx={{
                position: 'absolute',
                top: baseY,
                left: baseX,
                cursor: 'pointer',
                animation: isAnimating ? `fall ${duration}s linear infinite` : 'none',
                animationDelay: `${startDelay}s`,
                transform: `rotate(${rotation}deg) scale(${scale})`,
                transition: 'transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)',
                willChange: 'transform',
                opacity: loadedPhotos.has(photo._id) ? 1 : 0,
                backgroundColor: 'transparent',
                padding: 0,
                margin: 0,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '150px',
                height: '150px',
                '&:hover': {
                  transform: `rotate(${rotation}deg) scale(${scale * 1.1})`,
                  zIndex: 1,
                },
                '@keyframes fall': {
                  '0%': {
                    transform: `translateY(0) translateX(0) rotate(${rotation}deg) scale(${scale})`,
                    opacity: 0,
                  },
                  '2%': {
                    opacity: 1,
                  },
                  '98%': {
                    opacity: 1,
                  },
                  '100%': {
                    transform: `translateY(calc(100vh + 150px)) translateX(${horizontalSpeed * 150}px) rotate(${rotation + 360}deg) scale(${scale})`,
                    opacity: 0,
                  },
                },
              }}
            >
              <Box
                component="img"
                src={`${API_URL}/uploads/thumbnails/${photo.datePath}/${photo.filename}`}
                alt={photo.originalName}
                onError={() => handleImageError(photo._id)}
                onLoad={() => handleImageLoad(photo._id)}
                sx={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'contain',
                  borderRadius: '8px',
                  transition: 'all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)',
                  filter: 'drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1))',
                  willChange: 'transform, filter',
                  backgroundColor: 'transparent',
                  padding: 0,
                  margin: 0,
                  display: 'block',
                  mixBlendMode: 'normal',
                  animation: `float ${5 + Math.random() * 3}s ease-in-out infinite`,
                  '@keyframes float': {
                    '0%, 100%': {
                      transform: 'translateY(0) rotate(0deg)',
                    },
                    '50%': {
                      transform: 'translateY(-10px) rotate(5deg)',
                    },
                  },
                  '&:hover': {
                    filter: 'drop-shadow(0 8px 16px rgba(0, 0, 0, 0.15))',
                    transform: 'scale(1.05) rotate(5deg)',
                  },
                }}
              />
            </Box>
          ))
        )}
      </Box>
    </Box>
  );
}

// 新建相册对话框组件
function CreateAlbumDialog({ open, onClose, onSuccess }) {
  const [albumName, setAlbumName] = useState('');
  const [description, setDescription] = useState('');

  const handleSubmit = async () => {
    try {
      await axios.post(`${API_URL}/api/albums`, {
        name: albumName,
        description,
      });
      onSuccess();
      onClose();
      setAlbumName('');
      setDescription('');
    } catch (error) {
      console.error('创建相册失败:', error);
    }
  };

  return (
    <Dialog 
      open={open} 
      onClose={onClose}
      PaperProps={{
        sx: {
          borderRadius: 3,
          maxWidth: 400,
          width: '100%',
          bgcolor: '#2d2d2d',
          color: '#ffffff',
        },
      }}
    >
      <DialogTitle sx={{ 
        borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
        pb: 2,
      }}>
        创建新相册
      </DialogTitle>
      <DialogContent sx={{ pt: 3 }}>
        <TextField
          fullWidth
          label="相册名称"
          value={albumName}
          onChange={(e) => setAlbumName(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <CreateNewFolderIcon sx={{ color: 'rgba(255,255,255,0.7)' }} />
              </InputAdornment>
            ),
            sx: {
              '& input': {
                WebkitTextFillColor: '#ffffff !important', // 修复自动填充时的文字颜色
                '&:-webkit-autofill': {
                  WebkitBoxShadow: '0 0 0 100px #2d2d2d inset',
                  WebkitTextFillColor: '#ffffff',
                  transition: 'background-color 5000s ease-in-out 0s',
                },
              },
            },
          }}
          sx={{
            mb: 2,
            '& .MuiOutlinedInput-root': {
              color: '#ffffff',
              '& fieldset': {
                borderColor: 'rgba(255, 255, 255, 0.2)',
              },
              '&:hover fieldset': {
                borderColor: 'rgba(255, 255, 255, 0.3)',
              },
              '&.Mui-focused fieldset': {
                borderColor: 'primary.main',
              },
            },
            '& .MuiInputLabel-root': {
              color: 'rgba(255, 255, 255, 0.7)',
            },
          }}
        />
        <TextField
          fullWidth
          label="相册描述"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          multiline
          rows={3}
          InputProps={{
            sx: {
              '& input': {
                WebkitTextFillColor: '#ffffff !important', // 修复自动填充时的文字颜色
                '&:-webkit-autofill': {
                  WebkitBoxShadow: '0 0 0 100px #2d2d2d inset',
                  WebkitTextFillColor: '#ffffff',
                  transition: 'background-color 5000s ease-in-out 0s',
                },
              },
            },
          }}
          sx={{
            '& .MuiOutlinedInput-root': {
              color: '#ffffff',
              '& fieldset': {
                borderColor: 'rgba(255, 255, 255, 0.2)',
              },
              '&:hover fieldset': {
                borderColor: 'rgba(255, 255, 255, 0.3)',
              },
              '&.Mui-focused fieldset': {
                borderColor: 'primary.main',
              },
            },
            '& .MuiInputLabel-root': {
              color: 'rgba(255, 255, 255, 0.7)',
            },
          }}
        />
      </DialogContent>
      <DialogActions sx={{ px: 3, py: 2 }}>
        <Button 
          onClick={onClose}
          sx={{ 
            mr: 1,
            px: 3,
            py: 1,
            color: 'rgba(255, 255, 255, 0.7)',
            fontSize: '0.95rem',
            fontWeight: 500,
            textTransform: 'none',
            '&:hover': {
              color: '#ffffff',
              bgcolor: 'rgba(255, 255, 255, 0.1)',
            },
            transition: 'all 0.2s ease',
          }}
        >
          取消
        </Button>
        <Button 
          onClick={handleSubmit}
          variant="contained"
          disabled={!albumName.trim()}
          sx={{
            borderRadius: 2,
            px: 4,
            py: 1,
            fontSize: '0.95rem',
            fontWeight: 600,
            textTransform: 'none',
            background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
            boxShadow: '0 4px 20px rgba(33, 150, 243, 0.3)',
            '&:hover': {
              background: 'linear-gradient(45deg, #1976D2 30%, #1E88E5 90%)',
              boxShadow: '0 6px 25px rgba(33, 150, 243, 0.4)',
              transform: 'translateY(-1px)',
            },
            '&:active': {
              transform: 'translateY(1px)',
            },
            '&.Mui-disabled': {
              background: 'rgba(255, 255, 255, 0.12)',
              color: 'rgba(255, 255, 255, 0.3)',
            },
            transition: 'all 0.3s ease',
          }}
        >
          创建
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// 相册卡片组件
function AlbumCard({ album, onDelete, onClick, onRename }) {
  const [isHovered, setIsHovered] = useState(false);

  return (
    <Fade in={true}>
      <Card
        onClick={() => onClick(album)}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        sx={{
          borderRadius: 3,
          overflow: 'hidden',
          cursor: 'pointer',
          transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
          position: 'relative',
          bgcolor: 'rgba(255, 255, 255, 0.05)',
          backdropFilter: 'blur(10px)',
          border: '1px solid rgba(255, 255, 255, 0.1)',
          '&:hover': {
            transform: 'translateY(-8px)',
            boxShadow: '0 20px 40px rgba(0, 0, 0, 0.3)',
            border: '1px solid rgba(255, 255, 255, 0.2)',
          },
        }}
      >
        <Box sx={{ position: 'relative', paddingTop: '75%' }}>
          <CardMedia
            component="img"
            image={album.coverPhoto ? `${API_URL}/uploads/${album.coverPhoto}` : '/default-album.jpg'}
            alt={album.name}
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: '100%',
              objectFit: 'cover',
              transition: 'transform 0.5s ease',
              transform: isHovered ? 'scale(1.1)' : 'scale(1)',
            }}
          />
          <Box
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              background: 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.8) 100%)',
              opacity: isHovered ? 1 : 0,
              transition: 'opacity 0.3s ease',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 2,
              zIndex: 2,
            }}
          >
            <IconButton
              color="primary"
              onClick={(e) => {
                e.stopPropagation();
                onRename(album);
              }}
              sx={{
                bgcolor: 'rgba(255, 255, 255, 0.95)',
                width: 48,
                height: 48,
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)',
                '&:hover': {
                  bgcolor: '#ffffff',
                  transform: 'scale(1.1)',
                  boxShadow: '0 6px 16px rgba(0, 0, 0, 0.3)',
                },
                transition: 'all 0.3s ease',
              }}
            >
              <EditIcon sx={{ fontSize: 28 }} />
            </IconButton>
            <IconButton
              color="error"
              onClick={(e) => {
                e.stopPropagation();
                onDelete(album._id);
              }}
              sx={{
                bgcolor: 'rgba(255, 255, 255, 0.95)',
                width: 48,
                height: 48,
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.2)',
                '&:hover': {
                  bgcolor: '#ffffff',
                  transform: 'scale(1.1)',
                  boxShadow: '0 6px 16px rgba(0, 0, 0, 0.3)',
                },
                transition: 'all 0.3s ease',
              }}
            >
              <DeleteIcon sx={{ fontSize: 28 }} />
            </IconButton>
          </Box>
        </Box>
        <CardContent sx={{ 
          p: 3,
          background: 'rgba(255, 255, 255, 0.05)',
          backdropFilter: 'blur(10px)',
        }}>
          <Box sx={{ flex: 1 }}>
            <Typography 
              variant="h6" 
              component="div" 
              sx={{ 
                mb: 1,
                fontWeight: 600,
                color: '#ffffff',
                textShadow: '0 2px 4px rgba(0,0,0,0.2)',
              }}
            >
              {album.name}
            </Typography>
            <Typography 
              variant="body2" 
              sx={{
                color: 'rgba(255, 255, 255, 0.7)',
                display: '-webkit-box',
                WebkitLineClamp: 2,
                WebkitBoxOrient: 'vertical',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                lineHeight: 1.4,
              }}
            >
              {album.description || '暂无描述'}
            </Typography>
          </Box>
        </CardContent>
      </Card>
    </Fade>
  );
}

// 相册信息修改对话框组件
function EditAlbumDialog({ open, onClose, album, onSuccess }) {
  const [formData, setFormData] = useState({
    name: '',
    description: ''
  });

  useEffect(() => {
    if (album) {
      setFormData({
        name: album.name || '',
        description: album.description || ''
      });
    }
  }, [album]);

  const handleSubmit = async () => {
    try {
      await axios.patch(`${API_URL}/api/albums/${album?._id}`, {
        name: formData.name.trim(),
        description: formData.description.trim()
      });
      onSuccess();
      onClose();
    } catch (error) {
      console.error('修改相册信息失败:', error);
    }
  };

  const handleChange = (field) => (e) => {
    setFormData(prev => ({
      ...prev,
      [field]: e.target.value
    }));
  };

  return (
    <Dialog 
      open={open} 
      onClose={onClose}
      PaperProps={{
        sx: {
          borderRadius: 3,
          maxWidth: 400,
          width: '100%',
          bgcolor: '#2d2d2d',
          color: '#ffffff',
        },
      }}
    >
      <DialogContent sx={{ pt: 3 }}>
        <Stack spacing={2}>
          <TextField
            fullWidth
            label="相册名称"
            value={formData.name}
            onChange={handleChange('name')}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <EditIcon sx={{ color: 'rgba(255,255,255,0.7)' }} />
                </InputAdornment>
              ),
            }}
            sx={{
              '& .MuiOutlinedInput-root': {
                color: '#ffffff',
                '& fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.2)',
                },
                '&:hover fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.3)',
                },
                '&.Mui-focused fieldset': {
                  borderColor: 'primary.main',
                },
              },
              '& .MuiInputLabel-root': {
                color: 'rgba(255, 255, 255, 0.7)',
              },
            }}
          />
          <TextField
            fullWidth
            label="相册描述"
            value={formData.description}
            onChange={handleChange('description')}
            multiline
            rows={3}
            sx={{
              '& .MuiOutlinedInput-root': {
                color: '#ffffff',
                '& fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.2)',
                },
                '&:hover fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.3)',
                },
                '&.Mui-focused fieldset': {
                  borderColor: 'primary.main',
                },
              },
              '& .MuiInputLabel-root': {
                color: 'rgba(255, 255, 255, 0.7)',
              },
            }}
          />
        </Stack>
      </DialogContent>
      <DialogActions sx={{ px: 3, py: 2 }}>
        <Button 
          onClick={onClose}
          sx={{ 
            mr: 1,
            px: 3,
            color: 'rgba(255, 255, 255, 0.7)',
            '&:hover': {
              color: '#ffffff',
              bgcolor: 'rgba(255, 255, 255, 0.1)',
            },
          }}
        >
          取消
        </Button>
        <Button 
          onClick={handleSubmit}
          variant="contained"
          disabled={!formData.name.trim()}
          sx={{
            px: 4,
            background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
            '&:hover': {
              background: 'linear-gradient(45deg, #1976D2 30%, #1E88E5 90%)',
            },
          }}
        >
          确定
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// 照片卡片组件
function PhotoCard({ photo, onSelect, onDelete, onRename, isSelected, onPreview, previewIndex, previewList }) {
  return (
    <Card sx={{
      position: 'relative',
      borderRadius: 2,
      overflow: 'hidden',
      transition: 'all 0.3s ease',
      '&:hover': {
        transform: 'translateY(-4px)',
        boxShadow: '0 8px 24px rgba(0, 0, 0, 0.2)',
      },
    }}>
      <Box sx={{ position: 'relative' }}>
        <CardMedia
          component="img"
          height="200"
          image={`${API_URL}/uploads/thumbnails/${photo.datePath}/${photo.filename}`}
          alt={photo.originalName || '照片'}
          onClick={() => onPreview && onPreview(previewList, previewIndex)}
          sx={{
            cursor: 'pointer',
            objectFit: 'cover',
            transition: 'opacity 0.3s ease',
            '&.MuiCardMedia-root': {
              height: '200px',
              width: '100%',
              display: 'block'
            }
          }}
        />
        <IconButton
          sx={{
            position: 'absolute',
            top: 8,
            left: 8,
            zIndex: 1,
            bgcolor: isSelected ? 'primary.main' : 'rgba(0,0,0,0.5)',
            color: '#fff',
            borderRadius: '50%',
            p: 0.5,
            width: 32,
            height: 32,
            '&:hover': {
              bgcolor: isSelected ? 'primary.dark' : 'rgba(0,0,0,0.7)',
            },
            transition: 'all 0.2s',
          }}
          onClick={e => {
            e.stopPropagation();
            onSelect(photo);
          }}
        >
          <Checkbox
            checked={isSelected}
            sx={{
              color: '#fff',
              p: 0,
              '&.Mui-checked': { color: '#fff' },
            }}
          />
        </IconButton>
        <Box
          sx={{
            position: 'absolute',
            top: 8,
            right: 8,
            zIndex: 1,
            display: 'flex',
            gap: 1,
          }}
        >
          <IconButton
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              onRename(photo);
            }}
            sx={{
              bgcolor: 'rgba(0, 0, 0, 0.5)',
              color: 'white',
              borderRadius: '50%',
              '&:hover': {
                bgcolor: 'rgba(0, 0, 0, 0.7)',
              },
            }}
          >
            <EditIcon fontSize="small" />
          </IconButton>
          <IconButton
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              onDelete(photo._id);
            }}
            sx={{
              bgcolor: 'rgba(0, 0, 0, 0.5)',
              color: 'white',
              borderRadius: '50%',
              '&:hover': {
                bgcolor: 'rgba(0, 0, 0, 0.7)',
              },
            }}
          >
            <DeleteIcon fontSize="small" />
          </IconButton>
        </Box>
      </Box>
      <CardContent sx={{ p: 2 }}>
        <Typography variant="body2" noWrap>
          {photo.originalName}
        </Typography>
      </CardContent>
    </Card>
  );
}

function Album() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [album, setAlbum] = useState(null);
  const [albums, setAlbums] = useState([]);
  const [photos, setPhotos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedPhotos, setSelectedPhotos] = useState(new Set());
  const [showPhotoRain, setShowPhotoRain] = useState(false);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showRenameDialog, setShowRenameDialog] = useState(false);
  const [showRenameAlbumDialog, setShowRenameAlbumDialog] = useState(false);
  const [selectedPhoto, setSelectedPhoto] = useState(null);
  const [selectedAlbum, setSelectedAlbum] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadError, setUploadError] = useState(null);
  const [isUploading, setIsUploading] = useState(false);
  const [retryCount, setRetryCount] = useState(0);
  const maxRetries = 3;
  const fileInputRef = useRef(null);
  const preloadQueue = useRef([]);
  const isPreloading = useRef(false);
  const preloadedPhotos = useRef(new Set());
  const [imageLoadError, setImageLoadError] = useState(new Set());
  const [viewMode, setViewMode] = useState('grid');
  const [searchQuery, setSearchQuery] = useState('');
  const [uploadStatus, setUploadStatus] = useState('idle');
  const [uploadMessage, setUploadMessage] = useState('');
  const [downloadProgress, setDownloadProgress] = useState(0);
  const [downloadError, setDownloadError] = useState(null);
  const [downloadComplete, setDownloadComplete] = useState(false);
  const [newPhotoName, setNewPhotoName] = useState('');
  const [photoToRename, setPhotoToRename] = useState(null);
  const [newAlbumName, setNewAlbumName] = useState('');
  const [newAlbumDescription, setNewAlbumDescription] = useState('');
  const [albumToRename, setAlbumToRename] = useState(null);
  const [albumToEdit, setAlbumToEdit] = useState(null);
  const [previewPhotoIndex, setPreviewPhotoIndex] = useState(-1);
  const [previewPhotoList, setPreviewPhotoList] = useState([]);

  // 预加载图片
  const preloadImage = useCallback((url) => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = url;
    });
  }, []);

  // 处理预加载队列
  const processPreloadQueue = useCallback(() => {
    if (isPreloading.current || preloadQueue.current.length === 0) {
      return;
    }
    
    isPreloading.current = true;
    const photo = preloadQueue.current.shift();
    preloadImage(`${API_URL}/uploads/thumbnails/${photo.datePath}/${photo.filename}`)
      .then(() => {
        preloadedPhotos.current.add(photo._id);
      })
      .catch(error => {
        console.error('预加载图片失败:', error);
      })
      .finally(() => {
        isPreloading.current = false;
        processPreloadQueue();
      });
  }, [preloadImage]);

  // 添加照片到预加载队列
  const addToPreloadQueue = useCallback((photo) => {
    if (preloadedPhotos.current.has(photo._id)) {
      return;
    }
    preloadQueue.current.push(photo);
    processPreloadQueue();
  }, [processPreloadQueue]);

  // 加载相册数据
  const loadAlbumData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const [albumResponse, photosResponse] = await Promise.all([
        axios.get(`${API_URL}/api/albums/${id}`),
        axios.get(`${API_URL}/api/photos?albumId=${id}`)
      ]);

      setAlbum(albumResponse.data);
      setPhotos(photosResponse.data);
    } catch (err) {
      console.error('加载相册数据失败:', err);
      setError(err.response?.data?.message || '加载相册失败');
      
      // 如果是认证错误，重定向到登录页面
      if (err.response?.status === 401) {
        navigate('/login');
      }
    } finally {
      setLoading(false);
    }
  }, [id, navigate]);

  // 加载所有相册
  const loadAlbums = useCallback(async () => {
    try {
      const response = await axios.get(`${API_URL}/api/albums`);
      setAlbums(response.data);
    } catch (error) {
      console.error('加载相册列表失败:', error);
    }
  }, []);

  // 初始加载和重试逻辑
  useEffect(() => {
    if (retryCount < maxRetries) {
      loadAlbumData();
    }
  }, [loadAlbumData, retryCount]);

  // 加载相册列表
  useEffect(() => {
    loadAlbums();
  }, [loadAlbums]);

  // 当照片列表更新时，开始预加载
  useEffect(() => {
    if (photos.length > 0) {
      photos.forEach(photo => addToPreloadQueue(photo));
    }
  }, [photos, addToPreloadQueue]);

  if (loading) {
    return (
      <Box
        display="flex"
        justifyContent="center"
        alignItems="center"
        minHeight="100vh"
      >
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box
        display="flex"
        flexDirection="column"
        justifyContent="center"
        alignItems="center"
        minHeight="100vh"
        p={3}
      >
        <Typography variant="h5" color="error" gutterBottom>
          加载失败
        </Typography>
        <Typography color="textSecondary" gutterBottom>
          {error}
        </Typography>
        {retryCount < maxRetries && (
          <Button
            variant="contained"
            color="primary"
            onClick={() => setRetryCount(prev => prev + 1)}
            startIcon={<RefreshIcon />}
            sx={{ mt: 2 }}
          >
            重试
          </Button>
        )}
      </Box>
    );
  }

  const handleDeleteAlbum = async (albumId) => {
    try {
      await axios.delete(`${API_URL}/api/albums/${albumId}`);
      loadAlbumData();
    } catch (error) {
      console.error('删除相册失败:', error);
    }
  };

  // 优化图片上传
  const handleFileUpload = async (files) => {
    if (!files || files.length === 0) {
      return;
    }

    setUploadStatus('uploading');
    setUploadProgress(0);
    setUploadError(null);
    setUploadMessage('正在压缩和上传...');

    try {
      const compressedFiles = [];
      let totalSize = 0;
      let compressedSize = 0;

      // 压缩所有图片
      for (const file of files) {
        totalSize += file.size;
        
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
          throw new Error('不支持的文件类型');
        }

        // 根据文件类型设置不同的压缩选项
        let options;
        if (file.type === 'image/bmp') {
          // BMP格式特殊处理：转换为PNG格式以保持颜色质量
          options = {
            maxSizeMB: 2,
            maxWidthOrHeight: 2048,
            useWebWorker: true,
            initialQuality: 1, // 最高质量
            fileType: 'image/png', // 转换为PNG格式
            strict: true,
            alwaysKeepResolution: true,
            preserveHeaders: true
          };
        } else {
          // 其他格式使用普通压缩
          options = {
            maxSizeMB: 2,
            maxWidthOrHeight: 2048,
            useWebWorker: true,
            initialQuality: 0.9,
            fileType: file.type,
            strict: false,
            alwaysKeepResolution: true,
            preserveHeaders: true
          };
        }

        try {
          const compressedFile = await imageCompression(file, options);
          
          // 验证压缩后的文件
          if (compressedFile.size === 0) {
            throw new Error('压缩后的文件无效');
          }

          // 根据文件类型设置输出文件名和类型
          let outputFileName = file.name;
          let outputFileType = file.type;
          
          if (file.type === 'image/bmp') {
            // 如果是BMP，将扩展名改为.png
            outputFileName = file.name.replace(/\.bmp$/i, '.png');
            outputFileType = 'image/png';
          }

          // 创建新的文件对象
          const compressedFileWithType = new File(
            [compressedFile],
            outputFileName,
            { type: outputFileType }
          );

          compressedFiles.push(compressedFileWithType);
          compressedSize += compressedFileWithType.size;
        } catch (error) {
          console.error('压缩图片失败:', error);
          // 如果压缩失败，使用原图
          compressedFiles.push(file);
          compressedSize += file.size;
        }
      }

      if (compressedFiles.length === 0) {
        throw new Error('没有可上传的图片');
      }

      // 计算压缩率
      const compressionRatio = ((totalSize - compressedSize) / totalSize * 100).toFixed(1);
      setUploadMessage(`压缩完成，节省了 ${compressionRatio}% 的空间，正在上传...`);

      const formData = new FormData();
      for (const file of compressedFiles) {
        formData.append('photos', file);
      }
      formData.append('albumId', id);

      const response = await axios.post(
        `${API_URL}/api/photos/upload-multiple`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            setUploadProgress(percentCompleted);
            setUploadMessage(`上传中: ${percentCompleted}%`);
          },
        }
      );

      console.log('上传响应:', response.data);

      // 检查上传结果
      const { results } = response.data;
      if (results.success.length > 0) {
        setUploadStatus('success');
        setUploadMessage(`成功上传 ${results.success.length} 张照片`);
        
        // 更新照片列表
        setPhotos(prevPhotos => [...results.success, ...prevPhotos]);
        
        // 如果有失败的照片，显示错误信息
        if (results.failed.length > 0) {
          setUploadError(`${results.failed.length} 张照片上传失败`);
          console.error('上传失败的照片:', results.failed);
        }
      } else {
        setUploadStatus('error');
        setUploadMessage('没有照片上传成功');
        setUploadError('上传失败');
      }

    } catch (error) {
      console.error('上传照片失败:', error);
      setUploadStatus('error');
      const errorMessage = error.response?.data?.message || error.message || '上传失败，请重试';
      setUploadError(errorMessage);
      setUploadMessage(errorMessage);
    } finally {
      // 上传完成后至少显示一段时间，然后隐藏
      setTimeout(() => {
        setUploadStatus('idle');
        setUploadProgress(0);
        setUploadError(null);
        setUploadMessage('');
      }, 3000); // 显示 3 秒
    }
  };

  const handleDeletePhoto = async (photoId) => {
    try {
      setLoading(true);
      const response = await axios.delete(`${API_URL}/api/photos/${photoId}`);
      if (response.data.message === '照片已移入回收站') {
        // 重新加载相册数据
        await loadAlbumData();
        setError(null);
      } else {
        throw new Error('删除失败');
      }
    } catch (error) {
      console.error('删除照片失败:', error);
      setError(error.response?.data?.message || '删除照片失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 批量删除照片
  const handleBatchDelete = async () => {
    try {
      await Promise.all(Array.from(selectedPhotos).map(photoId => 
        axios.delete(`${API_URL}/api/photos/${photoId}`)
      ));
      setSelectedPhotos(new Set());
      loadAlbumData();
    } catch (error) {
      console.error('批量删除失败:', error);
    }
  };

  // 选择/取消选择照片
  const togglePhotoSelection = (photoId) => {
    setSelectedPhotos(prev => {
      const newSet = new Set(prev);
      if (newSet.has(photoId)) {
        newSet.delete(photoId);
      } else {
        newSet.add(photoId);
      }
      return newSet;
    });
  };

  const filteredAlbums = albums.filter(album => 
    album.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (album.description && album.description.toLowerCase().includes(searchQuery.toLowerCase()))
  );

  // 下载单张照片
  const downloadFile = async (photo) => {
    try {
      setDownloadProgress(0);
      setDownloadError(null);
      
      const response = await axios.get(`${API_URL}/api/photos/download/${photo._id}`, {
        responseType: 'blob',
        onDownloadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          setDownloadProgress(percentCompleted);
        }
      });

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', photo.originalName);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      
      setDownloadComplete(true);
      setTimeout(() => setDownloadComplete(false), 3000);
    } catch (error) {
      setDownloadError('下载失败，请重试');
      console.error('下载失败:', error);
    }
  };

  // 批量下载照片
  const downloadMultipleFiles = async () => {
    if (selectedPhotos.length === 0) return;
    
    try {
      setDownloadProgress(0);
      setDownloadError(null);
      
      const response = await axios.post(
        `${API_URL}/api/photos/download-multiple`,
        { photoIds: Array.from(selectedPhotos) },
        {
          responseType: 'blob',
          onDownloadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            setDownloadProgress(percentCompleted);
          }
        }
      );

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'photos.zip');
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      
      setDownloadComplete(true);
      setTimeout(() => setDownloadComplete(false), 3000);
    } catch (error) {
      setDownloadError('下载失败，请重试');
      console.error('批量下载失败:', error);
    }
  };

  // 下载相册
  const downloadAlbum = async () => {
    try {
      setDownloadProgress(0);
      setDownloadError(null);
      // 先刷新相册照片，确保数据最新
      const photosResponse = await axios.get(`${API_URL}/api/photos?albumId=${id}`);
      if (!photosResponse.data || photosResponse.data.length === 0) {
        setDownloadError('相册中没有可下载的照片');
        return;
      }
      const response = await axios.get(`${API_URL}/api/albums/${id}/download`, {
        responseType: 'blob',
        onDownloadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          setDownloadProgress(percentCompleted);
        }
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${albums.find(a => a._id === id)?.name || 'album'}.zip`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      setDownloadComplete(true);
      setTimeout(() => setDownloadComplete(false), 3000);
    } catch (error) {
      setDownloadError('下载失败，请重试');
      console.error('相册下载失败:', error);
    }
  };

  // 修改照片名称
  const handleRenamePhoto = async () => {
    if (!photoToRename || !newPhotoName.trim()) return;

    try {
      const response = await axios.patch(`${API_URL}/api/photos/${photoToRename._id}/rename`, {
        newName: newPhotoName.trim()
      });

      // 更新照片列表
      setPhotos(prevPhotos => 
        prevPhotos.map(photo => 
          photo._id === photoToRename._id ? response.data : photo
        )
      );

      setShowRenameDialog(false);
      setNewPhotoName('');
      setPhotoToRename(null);
    } catch (error) {
      console.error('修改照片名称失败:', error);
    }
  };

  // 打开重命名对话框
  const openRenameDialog = (photo) => {
    setPhotoToRename(photo);
    setNewPhotoName(photo.originalName);
    setShowRenameDialog(true);
  };

  // 处理相册信息修改
  const handleRenameAlbum = async () => {
    if (!albumToRename || !newAlbumName.trim()) return;

    try {
      const response = await axios.patch(`${API_URL}/api/albums/${albumToRename._id}`, {
        name: newAlbumName.trim(),
        description: newAlbumDescription.trim()
      });

      // 更新相册列表
      setAlbums(prevAlbums => 
        prevAlbums.map(album => 
          album._id === albumToRename._id ? response.data : album
        )
      );

      setShowRenameAlbumDialog(false);
      setNewAlbumName('');
      setNewAlbumDescription('');
      setAlbumToRename(null);
    } catch (error) {
      console.error('修改相册信息失败:', error);
    }
  };

  // 打开相册重命名对话框
  const openAlbumRenameDialog = (album) => {
    setAlbumToRename(album);
    setNewAlbumName(album.name);
    setNewAlbumDescription(album.description || '');
    setShowRenameAlbumDialog(true);
  };

  // Handle image loading errors in the photo grid
  const handleGridImageError = (photoId, error) => {
    console.error('图片加载失败:', {
      photoId,
      error,
      timestamp: new Date().toISOString()
    });
    setImageLoadError(prev => {
      const newSet = new Set(prev);
      newSet.add(photoId);
      return newSet;
    });
  };

  // Modify photo grid rendering
  const renderPhotoGrid = () => {
    const previewList = photos.map(p => ({
      ...p,
      src: `${API_URL}/uploads/thumbnails/${p.datePath}/${p.filename}`
    }));
    return (
      <Grid container spacing={3}>
        {photos.length > 0 ? (
          photos.map((photo, idx) => (
            <Grid item xs={12} sm={6} md={4} key={photo._id}>
              <PhotoCard
                photo={photo}
                onSelect={() => togglePhotoSelection(photo._id)}
                onDelete={handleDeletePhoto}
                onRename={openRenameDialog}
                isSelected={selectedPhotos.has(photo._id)}
                onPreview={openPreview}
                previewIndex={idx}
                previewList={previewList}
              />
            </Grid>
          ))
        ) : (
          <Grid item xs={12}>
            <Box sx={{ 
              display: 'flex', 
              flexDirection: 'column', 
              alignItems: 'center', 
              justifyContent: 'center',
              py: 4,
              textAlign: 'center'
            }}>
              <PhotoLibraryIcon sx={{ fontSize: 60, color: 'text.secondary', mb: 2 }} />
              <Typography variant="h6" color="text.secondary" gutterBottom>
                暂无照片
              </Typography>
              <Typography variant="body2" color="text.secondary">
                点击上方的"上传照片"按钮添加照片
              </Typography>
            </Box>
          </Grid>
        )}
      </Grid>
    );
  };

  const handleFileSelect = (event) => {
    const files = Array.from(event.target.files);
    const validFiles = files.filter(file => {
      if (file.size > 20 * 1024 * 1024) {
        setUploadError('文件大小不能超过20MB');
        return false;
      }
      const allowedTypes = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'image/bmp',
        'image/tiff',
        'image/svg+xml'
      ];
      if (!allowedTypes.includes(file.type)) {
        setUploadError('只支持 JPG、PNG、GIF、WebP、BMP、TIFF 和 SVG 格式的图片');
        return false;
      }
      return true;
    });

    if (validFiles.length > 0) {
      setUploadError(null);
      handleFileUpload(validFiles);
    } else {
      setUploadError('没有有效的文件可以上传');
    }
    
    // 清空文件输入，允许重复选择相同文件
    event.target.value = '';
  };

  // 打开编辑对话框
  const handleEditAlbum = (albumObj) => {
    if (!albumObj) return;
    setAlbumToEdit(albumObj);
    setShowEditDialog(true);
  };

  // 关闭编辑对话框
  const handleCloseEditDialog = () => {
    setShowEditDialog(false);
    setAlbumToEdit(null);
  };

  // 编辑成功后的处理
  const handleEditSuccess = () => {
    loadAlbumData(); // 编辑成功后刷新相册数据
    setShowEditDialog(false);
    setAlbumToEdit(null);
  };

  // 打开图片预览（支持多图）
  const openPreview = (photos, index) => {
    setPreviewPhotoList(photos);
    setPreviewPhotoIndex(index);
  };
  const closePreview = () => {
    setPreviewPhotoIndex(-1);
    setPreviewPhotoList([]);
  };
  const handlePreviewIndexChange = (idx) => setPreviewPhotoIndex(idx);

  return (
    <Box
      sx={{
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%)',
        py: 4,
      }}
    >
      <Container maxWidth="lg">
        {!id ? (
          // 相册列表页面
          <>
            <Box sx={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              mb: 6, 
              alignItems: 'center',
              position: 'relative',
            }}>
              <Typography 
                variant="h3" 
                component="h1" 
                sx={{ 
                  fontWeight: 700,
                  color: '#ffffff',
                  textShadow: '0 2px 4px rgba(0,0,0,0.2)',
                }}
              >
                我的相册
              </Typography>
              <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
                <TextField
                  size="small"
                  placeholder="搜索相册..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <SearchIcon sx={{ color: 'rgba(255,255,255,0.7)' }} />
                      </InputAdornment>
                    ),
                  }}
                  sx={{ 
                    width: 240,
                    '& .MuiOutlinedInput-root': {
                      borderRadius: 2,
                      bgcolor: 'rgba(255, 255, 255, 0.1)',
                      backdropFilter: 'blur(10px)',
                      color: '#ffffff',
                      '&:hover': {
                        bgcolor: 'rgba(255, 255, 255, 0.15)',
                      },
                      '& fieldset': {
                        borderColor: 'rgba(255, 255, 255, 0.2)',
                      },
                      '&:hover fieldset': {
                        borderColor: 'rgba(255, 255, 255, 0.3)',
                      },
                      '&.Mui-focused fieldset': {
                        borderColor: 'primary.main',
                      },
                    },
                    '& .MuiInputBase-input': {
                      color: '#ffffff',
                      '&::placeholder': {
                        color: 'rgba(255,255,255,0.5)',
                      },
                    },
                  }}
                />
                <Button
                  variant="outlined"
                  startIcon={<RestoreIcon />}
                  onClick={() => navigate('/trash')}
                  sx={{ borderRadius: 2, textTransform: 'none', px: 3 }}
                >
                  回收站
                </Button>
                <Button
                  variant="outlined"
                  color="error"
                  onClick={() => { localStorage.removeItem('token'); navigate('/login'); }}
                  sx={{ borderRadius: 2, textTransform: 'none', px: 3 }}
                >
                  退出登录
                </Button>
              </Box>
            </Box>

            <Grid container spacing={4}>
              {filteredAlbums.map((album) => (
                <Grid item xs={12} sm={6} md={4} key={album._id}>
                  <AlbumCard
                    album={album}
                    onDelete={handleDeleteAlbum}
                    onClick={(album) => navigate(`/album/${album._id}`)}
                    onRename={handleEditAlbum}
                  />
                </Grid>
              ))}
            </Grid>
          </>
        ) : (
          // 相册详情页面
          <>
            <Box sx={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              mb: 4,
              alignItems: 'center',
              flexDirection: { xs: 'column', sm: 'row' },
              gap: 2
            }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                <IconButton onClick={() => navigate('/')} sx={{ mr: 1 }}>
                  <ArrowBackIcon />
                </IconButton>
                <Typography variant="h4" component="h1" sx={{ 
                  fontWeight: 600, 
                  color: 'primary.main',
                  mt: 2,  // 增加顶部间距
                  mb: 1   // 增加底部间距
                }}>
                  {album?.name || '相册'}
                </Typography>
                {photos.length > 0 && (
                  <Button
                    variant="outlined"
                    startIcon={
                      <Checkbox 
                        checked={selectedPhotos.size === photos.length} 
                        sx={{
                          p: 0,
                          color: 'primary.main',
                          '&.Mui-checked': {
                            color: 'primary.main',
                          },
                        }}
                      />
                    }
                    onClick={() => {
                      if (selectedPhotos.size === photos.length) {
                        setSelectedPhotos(new Set());
                      } else {
                        setSelectedPhotos(new Set(photos.map(photo => photo._id)));
                      }
                    }}
                    sx={{ 
                      borderRadius: 2, 
                      textTransform: 'none', 
                      px: 3,
                      ml: 2,
                      color: 'primary.main',
                      borderColor: 'primary.main',
                      '&:hover': {
                        bgcolor: 'rgba(33, 150, 243, 0.08)',
                        borderColor: 'primary.dark',
                      },
                      '& .MuiButton-startIcon': {
                        marginRight: 1,
                      },
                      '@media (max-width: 600px)': {
                        ml: 0,
                        mt: 2,
                        width: '100%',
                      }
                    }}
                  >
                    {selectedPhotos.size === photos.length ? '取消全选' : '全选'}
                  </Button>
                )}
              </Box>
              <Box sx={{ display: 'flex', gap: 2, flexDirection: { xs: 'column', sm: 'row' } }}>
                <Button
                  variant="contained"
                  startIcon={<UploadIcon />}
                  onClick={() => fileInputRef.current?.click()}
                  sx={{ mr: { sm: 2 }, borderRadius: 2, textTransform: 'none', px: 3, width: { xs: '100%', sm: 'auto' } }}
                >
                  上传照片
                </Button>
                <Button
                  variant="outlined"
                  startIcon={<DownloadIcon />}
                  onClick={downloadAlbum}
                  sx={{ borderRadius: 2, textTransform: 'none', px: 3, width: { xs: '100%', sm: 'auto' } }}
                >
                  下载相册
                </Button>
                <Button
                  variant="outlined"
                  startIcon={<EditIcon />}
                  onClick={() => handleEditAlbum(album)}
                  sx={{ borderRadius: 2, textTransform: 'none', px: 3, width: { xs: '100%', sm: 'auto' } }}
                >
                  编辑相册信息
                </Button>
                <Button
                  variant="outlined"
                  startIcon={<RestoreIcon />}
                  onClick={() => navigate('/trash')}
                  sx={{ borderRadius: 2, textTransform: 'none', px: 3, width: { xs: '100%', sm: 'auto' } }}
                >
                  回收站
                </Button>
                <Button
                  variant="outlined"
                  startIcon={viewMode === 'grid' ? <PhotoLibraryIcon /> : <ViewModuleIcon />}
                  onClick={() => setViewMode(viewMode === 'grid' ? 'rain' : 'grid')}
                  sx={{ borderRadius: 2, textTransform: 'none', px: 3, width: { xs: '100%', sm: 'auto' } }}
                >
                  {viewMode === 'grid' ? '照片雨' : '网格视图'}
                </Button>
              </Box>
            </Box>

            {uploadError && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {uploadError}
              </Alert>
            )}

            {uploadStatus !== 'idle' && (uploadProgress > 0 || uploadStatus === 'success' || uploadStatus === 'error') && (
              <Box
                sx={{
                  position: 'fixed',
                  bottom: 20,
                  left: '50%',
                  transform: 'translateX(-50%)',
                  zIndex: 2000,
                  bgcolor: uploadStatus === 'error' ? 'error.main' : (uploadStatus === 'success' ? 'success.main' : 'rgba(0, 0, 0, 0.7)'),
                  color: 'white',
                  p: 2,
                  borderRadius: 1,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 2,
                  minWidth: 200, // 增加最小宽度
                  justifyContent: 'center',
                }}
              >
                {uploadStatus === 'uploading' && uploadProgress < 100 && (
                  <CircularProgress size={20} color="inherit" />
                )}
                <Typography variant="body2">
                  {uploadMessage}
                </Typography>
              </Box>
            )}

            {downloadError && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {downloadError}
              </Alert>
            )}

            {downloadProgress > 0 && (
              <LinearProgress 
                variant="determinate" 
                value={downloadProgress} 
                sx={{ mb: 2 }}
              />
            )}

            {downloadComplete && (
              <Alert severity="success" sx={{ mb: 2 }}>
                下载完成！
              </Alert>
            )}

            {selectedPhotos.size > 0 && (
              <Box sx={{ 
                display: 'flex', 
                gap: 2, 
                mb: 2, 
                flexDirection: { xs: 'column', sm: 'row' },
                position: 'sticky',
                top: 0,
                zIndex: 1000,
                bgcolor: 'rgba(45, 45, 45, 0.9)',
                backdropFilter: 'blur(10px)',
                p: 2,
                borderRadius: 2,
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)'
              }}>
                <Typography variant="subtitle1" sx={{ color: 'white', display: 'flex', alignItems: 'center' }}>
                  已选择 {selectedPhotos.size} 张照片
                </Typography>
                <Button
                  variant="outlined"
                  startIcon={<DownloadIcon />}
                  onClick={downloadMultipleFiles}
                  sx={{ 
                    borderRadius: 2, 
                    textTransform: 'none', 
                    px: 3, 
                    width: { xs: '100%', sm: 'auto' },
                    color: 'primary.main',
                    borderColor: 'primary.main',
                    '&:hover': {
                      borderColor: 'primary.dark',
                      bgcolor: 'rgba(33, 150, 243, 0.08)',
                    }
                  }}
                >
                  批量下载
                </Button>
                <Button
                  variant="outlined"
                  color="error"
                  startIcon={<DeleteIcon />}
                  onClick={handleBatchDelete}
                  sx={{ 
                    borderRadius: 2, 
                    textTransform: 'none', 
                    px: 3, 
                    width: { xs: '100%', sm: 'auto' },
                    '&:hover': {
                      bgcolor: 'rgba(244, 67, 54, 0.08)',
                    }
                  }}
                >
                  批量删除
                </Button>
                <Button
                  variant="outlined"
                  startIcon={<CloseIcon />}
                  onClick={() => setSelectedPhotos(new Set())}
                  sx={{ 
                    borderRadius: 2, 
                    textTransform: 'none', 
                    px: 3, 
                    width: { xs: '100%', sm: 'auto' },
                    color: 'text.secondary',
                    '&:hover': {
                      bgcolor: 'rgba(255, 255, 255, 0.08)',
                    }
                  }}
                >
                  取消选择
                </Button>
              </Box>
            )}

            {viewMode === 'grid' ? renderPhotoGrid() : (
              <Box sx={{ position: 'relative', height: 'calc(100vh - 200px)', overflow: 'hidden' }}>
                <PhotoRain 
                  photos={photos} 
                  onPhotoClick={(photo) => {
                    const index = photos.findIndex(p => p._id === photo._id);
                    openPreview(photos.map(p => ({
                      ...p,
                      src: `${API_URL}/uploads/thumbnails/${p.datePath}/${p.filename}`
                    })), index);
                  }} 
                  onClose={() => setViewMode('grid')}
                />
              </Box>
            )}

            <ImagePreviewDialog
              open={previewPhotoIndex >= 0}
              onClose={closePreview}
              images={previewPhotoList}
              currentIndex={previewPhotoIndex}
              onIndexChange={handlePreviewIndexChange}
            />
          </>
        )}
      </Container>

      <CreateAlbumDialog
        open={showCreateDialog}
        onClose={() => setShowCreateDialog(false)}
        onSuccess={loadAlbumData}
      />

      <EditAlbumDialog
        open={showEditDialog}
        onClose={handleCloseEditDialog}
        album={albumToEdit}
        onSuccess={handleEditSuccess}
      />

      {/* 重命名照片对话框 */}
      <Dialog
        open={showRenameDialog}
        onClose={() => {
          setShowRenameDialog(false);
          setNewPhotoName('');
          setPhotoToRename(null);
        }}
        PaperProps={{
          sx: {
            borderRadius: 3,
            maxWidth: 400,
            width: '100%',
            bgcolor: '#2d2d2d',
            color: '#ffffff',
          },
        }}
      >
        <DialogTitle sx={{ 
          borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
          pb: 2,
        }}>
          重命名照片
        </DialogTitle>
        <DialogContent sx={{ pt: 3 }}>
          <TextField
            fullWidth
            label="新名称"
            value={newPhotoName}
            onChange={(e) => setNewPhotoName(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <EditIcon sx={{ color: 'rgba(255,255,255,0.7)' }} />
                </InputAdornment>
              ),
              sx: {
                '& input': {
                  WebkitTextFillColor: '#ffffff !important',
                  '&:-webkit-autofill': {
                    WebkitBoxShadow: '0 0 0 100px #2d2d2d inset',
                    WebkitTextFillColor: '#ffffff',
                    transition: 'background-color 5000s ease-in-out 0s',
                  },
                },
              },
            }}
            sx={{
              '& .MuiOutlinedInput-root': {
                color: '#ffffff',
                '& fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.2)',
                },
                '&:hover fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.3)',
                },
                '&.Mui-focused fieldset': {
                  borderColor: 'primary.main',
                },
              },
              '& .MuiInputLabel-root': {
                color: 'rgba(255, 255, 255, 0.7)',
              },
            }}
          />
        </DialogContent>
        <DialogActions sx={{ px: 3, py: 2 }}>
          <Button 
            onClick={() => {
              setShowRenameDialog(false);
              setNewPhotoName('');
              setPhotoToRename(null);
            }}
            sx={{ 
              mr: 1,
              px: 3,
              py: 1,
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: '0.95rem',
              fontWeight: 500,
              textTransform: 'none',
              '&:hover': {
                color: '#ffffff',
                bgcolor: 'rgba(255, 255, 255, 0.1)',
              },
              transition: 'all 0.2s ease',
            }}
          >
            取消
          </Button>
          <Button 
            onClick={handleRenamePhoto}
            variant="contained"
            disabled={!newPhotoName.trim()}
            sx={{
              borderRadius: 2,
              px: 4,
              py: 1,
              fontSize: '0.95rem',
              fontWeight: 600,
              textTransform: 'none',
              background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
              boxShadow: '0 4px 20px rgba(33, 150, 243, 0.3)',
              '&:hover': {
                background: 'linear-gradient(45deg, #1976D2 30%, #1E88E5 90%)',
                boxShadow: '0 6px 25px rgba(33, 150, 243, 0.4)',
                transform: 'translateY(-1px)',
              },
              '&:active': {
                transform: 'translateY(1px)',
              },
              '&.Mui-disabled': {
                background: 'rgba(255, 255, 255, 0.12)',
                color: 'rgba(255, 255, 255, 0.3)',
              },
              transition: 'all 0.3s ease',
            }}
          >
            确定
          </Button>
        </DialogActions>
      </Dialog>

      {/* 相册信息修改对话框 */}
      <Dialog
        open={showRenameAlbumDialog}
        onClose={() => {
          setShowRenameAlbumDialog(false);
          setNewAlbumName('');
          setNewAlbumDescription('');
          setAlbumToRename(null);
        }}
        PaperProps={{
          sx: {
            borderRadius: 3,
            maxWidth: 400,
            width: '100%',
            bgcolor: '#2d2d2d',
            color: '#ffffff',
          },
        }}
      >
        <DialogTitle sx={{ 
          borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
          pb: 2,
        }}>
          修改相册信息
        </DialogTitle>
        <DialogContent sx={{ pt: 3 }}>
          <TextField
            fullWidth
            label="相册名称"
            value={newAlbumName}
            onChange={(e) => setNewAlbumName(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <EditIcon sx={{ color: 'rgba(255,255,255,0.7)' }} />
                </InputAdornment>
              ),
              sx: {
                '& input': {
                  WebkitTextFillColor: '#ffffff !important',
                  '&:-webkit-autofill': {
                    WebkitBoxShadow: '0 0 0 100px #2d2d2d inset',
                    WebkitTextFillColor: '#ffffff',
                    transition: 'background-color 5000s ease-in-out 0s',
                  },
                },
              },
            }}
            sx={{
              mb: 2,
              '& .MuiOutlinedInput-root': {
                color: '#ffffff',
                '& fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.2)',
                },
                '&:hover fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.3)',
                },
                '&.Mui-focused fieldset': {
                  borderColor: 'primary.main',
                },
              },
              '& .MuiInputLabel-root': {
                color: 'rgba(255, 255, 255, 0.7)',
              },
            }}
          />
          <TextField
            fullWidth
            label="相册描述"
            value={newAlbumDescription}
            onChange={(e) => setNewAlbumDescription(e.target.value)}
            multiline
            rows={3}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <CreateNewFolderIcon sx={{ color: 'rgba(255,255,255,0.7)' }} />
                </InputAdornment>
              ),
              sx: {
                '& textarea': {
                  WebkitTextFillColor: '#ffffff !important',
                  '&:-webkit-autofill': {
                    WebkitBoxShadow: '0 0 0 100px #2d2d2d inset',
                    WebkitTextFillColor: '#ffffff',
                    transition: 'background-color 5000s ease-in-out 0s',
                  },
                },
              },
            }}
            sx={{
              '& .MuiOutlinedInput-root': {
                color: '#ffffff',
                '& fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.2)',
                },
                '&:hover fieldset': {
                  borderColor: 'rgba(255, 255, 255, 0.3)',
                },
                '&.Mui-focused fieldset': {
                  borderColor: 'primary.main',
                },
              },
              '& .MuiInputLabel-root': {
                color: 'rgba(255, 255, 255, 0.7)',
              },
            }}
          />
        </DialogContent>
        <DialogActions sx={{ px: 3, py: 2 }}>
          <Button 
            onClick={() => {
              setShowRenameAlbumDialog(false);
              setNewAlbumName('');
              setNewAlbumDescription('');
              setAlbumToRename(null);
            }}
            sx={{ 
              mr: 1,
              px: 3,
              py: 1,
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: '0.95rem',
              fontWeight: 500,
              textTransform: 'none',
              '&:hover': {
                color: '#ffffff',
                bgcolor: 'rgba(255, 255, 255, 0.1)',
              },
              transition: 'all 0.2s ease',
            }}
          >
            取消
          </Button>
          <Button 
            onClick={handleRenameAlbum}
            variant="contained"
            disabled={!newAlbumName.trim()}
            sx={{
              borderRadius: 2,
              px: 4,
              py: 1,
              fontSize: '0.95rem',
              fontWeight: 600,
              textTransform: 'none',
              background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
              boxShadow: '0 4px 20px rgba(33, 150, 243, 0.3)',
              '&:hover': {
                background: 'linear-gradient(45deg, #1976D2 30%, #1E88E5 90%)',
                boxShadow: '0 6px 25px rgba(33, 150, 243, 0.4)',
                transform: 'translateY(-1px)',
              },
              '&:active': {
                transform: 'translateY(1px)',
              },
              '&.Mui-disabled': {
                background: 'rgba(255, 255, 255, 0.12)',
                color: 'rgba(255, 255, 255, 0.3)',
              },
              transition: 'all 0.3s ease',
            }}
          >
            确定
          </Button>
        </DialogActions>
      </Dialog>

      <input
        type="file"
        ref={fileInputRef}
        style={{ display: 'none' }}
        multiple
        accept="image/*"
        onChange={handleFileSelect}
      />
    </Box>
  );
}

export default Album; 